package com.hfzy.ihk.web.linkcall.controller.flow.record;

import com.hfzy.ihk.common.util.FileUtils;
import com.hfzy.ihk.common.util.Utils;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.common.web.WebResult;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingFlowStep;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingPackage;
import com.hfzy.ihk.facade.linkcall.entity.knowledge.KnowledgeBase;
import com.hfzy.ihk.facade.linkcall.enums.UploadRecordFileType;
import com.hfzy.ihk.facade.linkcall.vo.service.RecordFilePackageVo;
import com.hfzy.ihk.facade.linkcall.vo.service.RecordFileVo;
import com.hfzy.ihk.web.linkcall.biz.KnowledgeBase.KnowledgeBaseBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingFlowStepBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingPackageBiz;
import com.hfzy.ihk.web.linkcall.conf.PublicConfig;
import com.hfzy.ihk.web.linkcall.context.SpeechFunctionInitBean;
import com.hfzy.ihk.web.linkcall.controller.callTask.LinkageCallController;
import com.hfzy.ihk.web.linkcall.support.tts.SpeechSynthesizerMultiThread;
import com.hfzy.ihk.web.linkcall.utils.WebResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 录音管理类
 * */
@Controller
@RequestMapping("/records")
public class RecordController {
    Logger logger = LoggerFactory.getLogger(LinkageCallController.class);

    @Autowired
    SpeakingFlowStepBiz speakingFlowStepBiz;

    @Autowired
    SpeakingPackageBiz speakingPackageBiz;

    @Autowired
    KnowledgeBaseBiz knowledgeBaseBiz;


    /**
     * 添加用户分支界面
     * */
    @RequestMapping("/queryRecordsByPackageId")
    public  String saveOrUpdateCustomerAnswerWay(@RequestParam String packageId, Model model){
        model.addAttribute("packageId",packageId);
        model.addAttribute("uploadRecordFileTypes",UploadRecordFileType.values());
        model.addAttribute("selUploadRecordType",UploadRecordFileType.SPEAKINGFLOWSTEP);
        return "page/flow/record/queryRecordsByPackageId";
    }


    /**
     * 录音管理
     * @param  params                           查询的参数信息
     * @return WebResult
     * */
    @ResponseBody
    @RequestMapping("/queryRecordsByPackageIdPage")
    public  WebResult  queryFlowRecordsByPackageId(@RequestParam Map<String,String> params) {
        WebResult webResult = WebResultUtils.getFailCharWebResult("");
        try{
            if(!params.containsKey("packageId") || !params.containsKey("uploadRecordFileTypeStr")){
                return WebResultUtils.getFailCharWebResult("参数异常");
            }
            SpeakingPackage speakingPackage = speakingPackageBiz.getSpeakingPackageById(params.get("packageId"));
            if(speakingPackage == null){
                return WebResultUtils.getFailCharWebResult("参数异常");
            }
            UploadRecordFileType uploadRecordFileType = UploadRecordFileType.fromValue(params.get("uploadRecordFileTypeStr"));
            if(params==null){
                params = new HashMap<String,String>();
            }
            //根据该packageId 获取所有的话术
            Long timeStamp = System.currentTimeMillis();
            if (params.containsKey("timeStamp")) {
                timeStamp = Long.parseLong(params.get("timeStamp").toString());
            }
            Date createTime = Utils.long2Date(timeStamp);
            String createTimeEnd = Utils.date2DateTimeString(createTime);
            params.put("createTimeEnd", createTimeEnd);
            params.put("contentNoEmpty", "");
            params.put("packageId", params.get("packageId"));

            switch (uploadRecordFileType){
                case SPEAKINGFLOWSTEP:
                    if(params.containsKey("name")){
                        params.put("stepName",params.get("name"));
                        params.remove("name");
                    }
                    Page<SpeakingFlowStep> speakingFlowSteps = speakingFlowStepBiz.getSpeakingFlowStepByPage(params);
                    List<RecordFileVo> recordFileVos = new ArrayList<RecordFileVo>();
                    if(speakingFlowSteps.getContent()!=null && !speakingFlowSteps.getContent().isEmpty()){
                        for (SpeakingFlowStep speakingFlowStep:speakingFlowSteps){
                            RecordFileVo recordFileVo = new RecordFileVo();
                            recordFileVo.setId(speakingFlowStep.getId());
                            recordFileVo.setContent(speakingFlowStep.getContent());
                            recordFileVo.setName(speakingFlowStep.getStepName());
                            recordFileVo.setHadUploadFile(speakingFlowStep.getHadUploadFile());
                            recordFileVo.setUploadRecordFileType(UploadRecordFileType.SPEAKINGFLOWSTEP.getValue());
                            recordFileVo.setUploadRecordFileTypeDesc(UploadRecordFileType.SPEAKINGFLOWSTEP.getDesc());
                            recordFileVo.setRecordFileUrl(speakingFlowStep.getRecordFileUrl());
                            recordFileVo.setIndex("");
                            recordFileVo.setType(speakingFlowStep.getType().getValue());
                            recordFileVo.setPackageId(speakingFlowStep.getPackageId());
                            recordFileVo.setFlowId(speakingFlowStep.getFlowId());
                            recordFileVos.add(recordFileVo);
                        }
                    }
                    webResult = WebResultUtils.getSuccessCharWebResult("",speakingFlowSteps.getTotalElements(),recordFileVos);
                    break;
                case KNOWLEDGE:
                    if(params.containsKey("name")){
                        params.put("title",params.get("name"));
                        params.remove("name");
                    }
                    Page<KnowledgeBase> knowledgeBasePage =  knowledgeBaseBiz.getKnowledgeBaseByPage(params);
                    List<RecordFilePackageVo> recordFilePackageVos = new ArrayList();
                    List<RecordFileVo> recordFileVos1 = new ArrayList<RecordFileVo>();
                    if(knowledgeBasePage.getContent()!=null && !knowledgeBasePage.getContent().isEmpty()){
                        for(KnowledgeBase knowledgeBase:knowledgeBasePage.getContent()){
                            if(knowledgeBase.getKnowledgeBaseResultVos()!=null && !knowledgeBase.getKnowledgeBaseResultVos().isEmpty()){
                                for(int i=0;i<knowledgeBase.getKnowledgeBaseResultVos().size();i++){
                                    RecordFileVo recordFileVo = new RecordFileVo();
                                    recordFileVo.setId(knowledgeBase.getId());
                                    recordFileVo.setContent(knowledgeBase.getKnowledgeBaseResultVos().get(i).getContent());
                                    recordFileVo.setName(knowledgeBase.getTitle());
                                    recordFileVo.setUploadRecordFileType(UploadRecordFileType.KNOWLEDGE.getValue());
                                    recordFileVo.setUploadRecordFileTypeDesc(UploadRecordFileType.KNOWLEDGE.getDesc());
                                    recordFileVo.setRecordFileUrl(knowledgeBase.getKnowledgeBaseResultVos().get(i).getRecordFileUrl()!=null?knowledgeBase.getKnowledgeBaseResultVos().get(i).getRecordFileUrl():"");
                                    recordFileVo.setIndex(knowledgeBase.getKnowledgeBaseResultVos().get(i).getId());
                                    recordFileVo.setPackageId(knowledgeBase.getPackageId());
                                    recordFileVos1.add(recordFileVo);
                                }
                            }
/*
                            RecordFilePackageVo recordFilePackageVo = new RecordFilePackageVo();
                            recordFilePackageVo.setPageckName(knowledgeBase.getTitle());
                            recordFilePackageVo.setId(knowledgeBase.getId());
                            recordFilePackageVo.setModTime(knowledgeBase.getModTime());
                            recordFilePackageVo.setModeTimeStr(Utils.date2DateString(knowledgeBase.getModTime()));
                            if(knowledgeBase.getOneToOneResult()!=null && !knowledgeBase.getOneToOneResult().isEmpty()){
                                int totalCount = knowledgeBase.getOneToOneResult().size();
                                recordFilePackageVo.setTotalNum(knowledgeBase.getOneToOneResult().size());
                                if(knowledgeBase.getResultRecordFile()!=null && !knowledgeBase.getResultRecordFile().isEmpty()){
                                    int finshedCount = knowledgeBase.getOneToOneResult().size()-knowledgeBase.getOneToOneResult().size();
                                    recordFilePackageVo.setFinishedNum(finshedCount>totalCount?totalCount:finshedCount);
                                }else{
                                    recordFilePackageVo.setFinishedNum(knowledgeBase.getOneToOneResult().size());
                                }
                            }
                            recordFilePackageVo.setUploadRecordFileType(UploadRecordFileType.SPEAKINGFLOWSTEP.getValue());
                            String finishProgess = "0";
                            if(recordFilePackageVo.getFinishedNum()>0 && recordFilePackageVo.getTotalNum()>0){
                                DecimalFormat decimalFormat = new DecimalFormat("0");
                                finishProgess = decimalFormat.format(Utils.getRate(recordFilePackageVo.getFinishedNum(),recordFilePackageVo.getTotalNum())*100);
                            }
                            recordFilePackageVo.setFinishProgess(finishProgess);
                            recordFilePackageVos.add(recordFilePackageVo);*/
                        }
                    }
                    webResult = WebResultUtils.getSuccessCharWebResult("",knowledgeBasePage.getTotalElements(),recordFileVos1);
                    break;
                default:
                    webResult = WebResultUtils.getFailCharWebResult("参数异常");
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
            webResult = WebResultUtils.getExceptionCharWebResult("");
        }
        return  webResult;
    }



    /**
     * 合成录音
     * */
    @ResponseBody
    @RequestMapping("/composeSpeechById")
    public  String  composeSpeechById(@RequestParam String id,@RequestParam String uploadRecordFileTypeStr,@RequestParam int index,HttpServletRequest request){
        SpeechSynthesizerMultiThread speechSynthesizerMultiThread = new SpeechSynthesizerMultiThread();
        boolean flag = false;
        try {
            UploadRecordFileType uploadRecordFileType = UploadRecordFileType.fromValue(uploadRecordFileTypeStr);
            String line= File.separator;
            File filePath = new File(PublicConfig.RECORDFILEPATH);
            if (!filePath.exists()) {
                filePath.createNewFile();
            }
            //上传音频文件
            String recordType = "composeSpeech";
            String  type  = "mp3";//阿里云的是MP3
            String serverName = request.getServerName();
            String recordType2 = uploadRecordFileType.getValue();
            switch (uploadRecordFileType) {
                case SPEAKINGFLOWSTEP:
                    SpeakingFlowStep speakingFlowStep = speakingFlowStepBiz.getSpeakingFlowStepById(id);

                    String recordFilePath = filePath+line+recordType+line+recordType2+line+type+line+Utils.date2String(new Date(),"yyyyMMdd")+line;
                    String fileName = id+"."+type;
                    FileUtils.checkAndCreateDir(recordFilePath);
                    FileUtils.createFile(recordFilePath,fileName);
                    if(!Utils.isNullString(speakingFlowStep.getContent())){
                        String content  =  speakingFlowStep.getContent();
                        if(content.contains("(") && content.contains(")")){
                            String delContent = content.substring(content.indexOf("("),content.indexOf(")")+1);
                            content = content.replace(delContent,"");
                            System.out.println(content);
                        }
                        flag = speechSynthesizerMultiThread.doTextToSpeech(SpeechFunctionInitBean.getSpeechSynthesizerExecutor(),recordFilePath+fileName,content);
                        System.out.println(recordFilePath+fileName);
                        /*ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                        HttpServletRequest request = requestAttributes.getRequest();*/
                        if("localhost".equals(serverName)){
                            serverName = "172.16.6.92";
                        }
                        //访问录音的路径
                        String urlPath = StringUtil.strConnect("recordFile",
                                "/","getRecord","/",recordType,"/",type,"/",recordType2,"/",Utils.date2String(new Date(),"yyyyMMdd")+"/"+fileName.substring(0,fileName.lastIndexOf(".")));
                        String url = ("http://" + serverName + ":" +request.getServerPort()+request.getContextPath() +"/"+ urlPath);
                        System.out.println(url);
                        speakingFlowStep.setHadUploadFile(true);
                        speakingFlowStep.setRecordFileUrl(url);
                        speakingFlowStep.setModTime(new Date());
                        speakingFlowStepBiz.saveSpeakingFlowStep(speakingFlowStep);
                    }
                    break;
                case KNOWLEDGE:
                    Map<String,String> queryParams = new HashMap<>();
                    queryParams.put("id",id);
//                    KnowledgeBase knowledgeBase = Utils.getFirst(knowledgeBaseBiz.getKnowledgeBaseList(queryParams));
                    KnowledgeBase knowledgeBase = Utils.getFirst(knowledgeBaseBiz.getKnowledgeBaseList(queryParams));
                    String recordFilePath_2 = filePath+line+recordType+line+recordType2+line+type+line+Utils.date2String(new Date(),"yyyyMMdd")+line;
                    String fileName_2 = id+"."+type;
                    FileUtils.checkAndCreateDir(recordFilePath_2);
                    FileUtils.createFile(recordFilePath_2,fileName_2);
                    if(knowledgeBase.getOneToOneResult()!=null && !knowledgeBase.getOneToOneResult().isEmpty()){
                        String content  =  knowledgeBase.getOneToOneResult().get(index);
                        if(content.contains("(") && content.contains(")")){
                            String delContent = content.substring(content.indexOf("("),content.indexOf(")")+1);
                            content = content.replace(delContent,"");
                            System.out.println(content);
                        }
                        flag = speechSynthesizerMultiThread.doTextToSpeech(SpeechFunctionInitBean.getSpeechSynthesizerExecutor(),recordFilePath_2+fileName_2,content);
                        System.out.println(recordFilePath_2+fileName_2);
                        //访问录音的路径
                        String urlPath = StringUtil.strConnect("recordFile",
                                "/","getRecord","/",recordType,"/",type,"/",recordType2,"/",Utils.date2String(new Date(),"yyyyMMdd")+"/"+fileName_2.substring(0,fileName_2.lastIndexOf(".")));
                        String url = ("http://" + serverName + ":" +request.getServerPort()+request.getContextPath() +"/"+ urlPath);
                        System.out.println(url);
                        //目前没有修改操作===只有录音上传操作，所以录了将新的add进去 ==== 之前录的则会被覆盖
                        LinkedHashMap<String, String>  resultRecordFile = knowledgeBase.getResultRecordFile();
                        if(resultRecordFile!=null && resultRecordFile.containsKey(""+index)){
                            resultRecordFile.remove(""+index);
                        }else{
                            resultRecordFile = new LinkedHashMap<>();
                        }
                        resultRecordFile.put(""+index,url);
                        if(resultRecordFile.size() >= knowledgeBase.getOneToOneResult().size()){
                            knowledgeBase.setHadUploadFile(true);
                        }
//                      小程序一次只可以上传一条录音--》因此加上index标识上传哪条回答的录音 --》目前上传接口 仅处理单个录音'
                        knowledgeBase.setResultRecordFile(resultRecordFile);
                        knowledgeBase.setModTime(new Date());
                        knowledgeBaseBiz.update(knowledgeBase);
                    }
                    break;
                default:
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag+"";
    }
}
